package main

import (
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"time"
)

var (
	errNoIp = errors.New("not mush ip")
)

var (
	defaultConfigName    = "config.yaml"
	defaultConfigPath, _ = os.Getwd()
	// 命令行参数
	confPath     = flag.String("config.path", defaultConfigPath, "Config Path.")
	confName     = flag.String("config.name", defaultConfigName, "default name 'config.yaml'")
	createConfig = flag.Bool("config.create", false, "create config file")
	interval     = flag.Int("interval", 600, "interval time(seconds)")
	daemonMode   = flag.Bool("daemon", false, "daemon mode")
	//logLevel   = flag.String("log.level", "info", "debug or info")
	configFile = ""
)

func main() {
	flag.Parse()

	configFile = *confPath + "/" + *confName
	var err error
	if *createConfig {
		err = createConfigFile(configFile)
		if err != nil {
			panic(fmt.Errorf("fatal error config file: %s", err))
		}
		return
	}
	cfg, err := LoadFile(configFile)
	if err != nil { // 处理读取配置文件的错误
		panic(fmt.Errorf("fatal error config file: %s", err))
	}

	var updateDomainCron = func() {
		var ownip string
		ownip, err = getIPSwitch(cfg.GetIPConfig)
		if err != nil {
			log.Println(err)
			return
		}
		log.Println("own ip is :", ownip)
		domainDNSHandler(cfg.DnsOrgConfig, ownip)
	}
	if *daemonMode {
		for {
			updateDomainCron()
			// 间隔
			time.Sleep(time.Duration(*interval) * time.Second)
			/*
				select {
				case <-time.After(time.Duration(*interval) * time.Second):
					updateDomainCron()
				}
			*/
		}
	} else {
		updateDomainCron()
	}
}

func domainDNSHandler(cfg DnsOrgConfig, ip string) bool {
	switch cfg.DnsOrg {
	case AliDNS:
		client, domain, err := aliyunCheckDomain(cfg.Aliyun, cfg.SubDomain)
		if err != nil {
			log.Printf("aliyun check domain error: %s \n", err)
			return false
		}
		domain.updateDomain(client, ip)
	default:
		return false
	}
	return true
}
